var xmlUserDoc = null;
var updatedUser = new Array();
var xsl = null;
var xmlProductDoc = null;
window.onbeforeunload = Call;
function Call() {
    // alert(xmlUserDoc);
    var url
    if (xmlUserDoc != null) {
        url = "../admin/sendXmlUser.html";
        sendDomToServer(xmlUserDoc, url, callBackFunctionForSendXMLToServer, updatedUser)
    }
    if (xmlProductDoc != null) {
        url = "../adminproduct/sendXmlProduct.html";
        sendProductDomToServer(xmlProductDoc, url, callBackFunctionForSendXMLToServer, updatedProduct)
    }
}

//Delete user on client
function deleteUser(id, userTableId) {
    var confirmDelete = confirm("Are you sure?");
    if (confirmDelete == true) {
        var xmlHttp = getXMLObject();
        var url = "../admin/delete.html?userId="+id;

        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if (xmlHttp.responseText == "OK") {
                    var table = document.getElementById("tblUser");
                    var deleteButton = table.rows[userTableId].cells[6].childNodes[0].innerHTML;
                    var checkIsDeleted = table.rows[userTableId].cells[3].childNodes[0];
                    if (deleteButton == "Delete") {
                        checkIsDeleted.checked = true;
                        table.rows[userTableId].cells[6].childNodes[0].innerHTML = "UnDelete"
                    } else if (deleteButton == "UnDelete") {
                        checkIsDeleted.checked = false;
                        table.rows[userTableId].cells[6].childNodes[0].innerHTML = "Delete"
                    }
                } else {
                    setTimeout(function(){
                        window.location.href = "../error/error.html"
                    },500);
                }
            }
        }
        xmlHttp.open("POST", url, true);
        xmlHttp.send();
    } 
}

function loadXML(url) {
    var xml;
    var xmlHttp = getXMLObject();

    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) {
            if(xmlHttp.status == 200) {
                xml = xmlHttp.responseXML;

            }
        }
    }
    xmlHttp.open("POST", url, false);
    xmlHttp.send();
    return xml;
}

//Load userXMLFile from server
function loadUserXMlFile(id, form) {
    if (xmlUserDoc == null) {    
        var url = "../admin/receiveuxml.html";

        xmlUserDoc = loadXML(url);
    }
    updateUser(id, form);
    //Not loading page again.
    return false;
//    return xmlUserNode;

}

//Create new User object
function User(id, username, firstname, lastname, address, phoneNumber, email) {
    var user = new Object();
    user.id = id;
    user.username = username;
    user.firstname = firstname;
    user.lastname = lastname;
    user.address = address;
    user.phoneNumber = phoneNumber;
    user.email = email;

    return user;
}

//Update user on client
function updateUser(id, formName) {
   var form = document.forms[""+formName];
//    var id = form.id.value;

    var username = "";
//    if (form.username) {
//        username = form.username.value;
//    }
    
    var firstname = form.firstname.value;
    var lastname = form.lastname.value;
    var address = form.address.value;
    var phoneNumber = form.phoneNumber.value;
    var email = form.email.value;
    
    var user = User(id, username,firstname, lastname, address, phoneNumber, email);

    var path = "/u:users/u:user[@id = '"+ user.id +"']";

    if (xmlUserDoc.evaluate) {
        var iterator = xmlUserDoc.evaluate(path, xmlUserDoc, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE ,null);

        try {
            //Update DOM
            //iterator.singleNodeValue.getElementsByTagName("username")[0].textContent = user.username;
            iterator.singleNodeValue.getElementsByTagName("firstname")[0].textContent = user.firstname;
            iterator.singleNodeValue.getElementsByTagName("lastname")[0].textContent = user.lastname;
            iterator.singleNodeValue.getElementsByTagName("address")[0].textContent = user.address;
            iterator.singleNodeValue.getElementsByTagName("phoneNumber")[0].textContent = user.phoneNumber;
            iterator.singleNodeValue.getElementsByTagName("email")[0].textContent = user.email;            
        }catch (e) {
            alert('Error : Document tree when updating.' + e);
        }
        //updateUserRow(user, userTableId);
        alert("Update successful.");
        //Add id to updatedUsers
        addIdToUpdatedList(user.id);

        document.getElementById('close').click();     
    } else {
        alert("Update fail. Please try again.")
    }

}

//Update user row in user's table
function updateUserRow(user, id) {
    var table = document.getElementById("tblUser");
    table.rows[id].cells["fullname"].innerHTML = user.firstname + " " + user.lastname;
    table.rows[id].cells["address"].innerHTML = user.address;
}

function callBackFunctionForSendXMLToServer(xmlHttp) {
    if (xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
            alert("OK");
        }
    }
}

function nsResolver(prefix) {
    var ns = {
        'u' : 'http://xml.netbeans.org/schema/',
        'p': 'http://xml.netbeans.org/schema/profile'
    };
    return ns[prefix] || null;
}

function addIdToUpdatedList(id) {
    var isfound = true;
       
    for (var i = 0; isfound && i < updatedUser.length; ++i) {
        if (updatedUser[i] == id) {
            isfound = false;
        }
    }
    if (isfound) {
        updatedUser.push(id);
    }
}

var fieldToSort = "username";
var sortOrder = "ascending";
function sort(field, id) {
    //Load doc

    if (fieldToSort == field) {
        sortOrder = (sortOrder == "ascending") ? "descending" : "ascending";
    } else {
        fieldToSort = field;
        sortOrder = "ascending";
    }

    
    var xml;
    if (xmlUserDoc == null) {
        xml = loadXML("../admin/receiveuxml.html");
    } else {
        xml = xmlUserDoc;
    }

    if (xsl == null) {
         xsl = loadXML("../admin/receivestylesheet.html");
    }


    if (document.implementation && document.implementation.createDocument) {
        var xsltProcessor=new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        //Get sort parameter
        xsltProcessor.setParameter(null, "fieldToSort", field);
        xsltProcessor.setParameter(null, "sortCondition", sortOrder);
        resultDocument = xsltProcessor.transformToFragment(xml,document);
        document.getElementById("concaculate").innerHTML = "";
        document.getElementById("concaculate").appendChild(resultDocument);

        document.getElementById(id).className = (sortOrder == "ascending") ? "sorting_desc": "sorting_asc";
    }
}

setInterval(function(){
    var pops = document.querySelectorAll(".popup");
    for(var i=0;i<pops.length;i++){
        var p = pops[i];
        p.style.left = "-webkit-calc((100% - "+p.offsetWidth+"px)/2)";
        p.style.top = "-webkit-calc((100% - "+p.offsetHeight+"px)/2)";
    }    
},500)